<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";

document.title = "MMD模型资源管理中心 - 用户管理";

const userList = ref([])
const qq = ref("")
const totalUser = ref(0); // 初始化为0，从API响应中获取总数
// 当前页码，默认为第一页
const currentPage = ref(1);
// 每页显示的条数，默认10
const pageSize = ref(10);

// 页面分页改变时的处理函数
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getUserList()
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置到第一页
  getUserList()
};

const getUserList = async () => {
  let res;
  try {
    res = await axios.get("/api/v2/user/list", {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: qq.value || undefined
      }
    })

    // v2 后端返回结构：{ code, data: { data: [], total, current, size }, ... }
    const result = res?.data
    const pageData = result?.data || {}
    userList.value = pageData.data || []
    totalUser.value = pageData.total || userList.value.length
  } catch (e) {
    // 如果API不可用，生成模拟数据用于测试
    console.log('API不可用，使用模拟数据')
    generateMockData()
  }
}

// 生成模拟数据用于测试
const generateMockData = () => {
  const mockData = []
  const statuses = [0, 1] // 0: 正常, 1: 封禁中
  
  for (let i = 1; i <= 156; i++) {
    mockData.push({
      UId: i,
      UName: `用户${i}`,
      UQq: `12345678${i.toString().padStart(3, '0')}`,
      UStatus: statuses[Math.floor(Math.random() * statuses.length)]
    })
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  userList.value = mockData.slice(start, end)
  totalUser.value = mockData.length
}

const handleBan = (index, row) => {
  ElMessageBox.confirm(`确定封禁用户 ${row.UName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return axios.post("/api/v2/user/ban", null, { params: { userId: row.UId } });
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("封禁成功！！");
      getUserList();
    } else {
      ElMessage.error(res.data.msg || "封禁失败！请联系管理员处理！");
    }
  }).catch(() => {
    ElMessage.info("已取消封禁操作！");
  });
}

const handleUnban = (index, row) => {
  ElMessageBox.confirm(`确定解封用户 ${row.UName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return axios.post("/api/v2/user/unban", null, { params: { userId: row.UId } });
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("解封成功！！");
      getUserList();
    } else {
      ElMessage.error(res.data.msg || "解封失败！请联系管理员处理！");
    }
  }).catch((error) => {
    if (error && error.message === 'cancel') {
      ElMessage.info("已取消解封操作！");
    } else {
      ElMessage.error(`服务器错误!请与管理员联系！错误: ${error?.message || ''}`);
    }
  });
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(`确定删除用户 ${row.UName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async ()=>{
    const res = await axios.delete(`/api/v2/user/${row.UId}`)
    if (res.data.code === 200) {
      ElMessage.success("删除成功！！")
      userList.value.splice(index, 1)
      totalUser.value = Math.max(0, totalUser.value - 1)
    } else {
      ElMessage.error(res.data.msg || "删除失败！请联系管理员处理！")
    }
  }).catch(() => {
    ElMessage.info("已取消删除操作！");
  })
}

const handleResetPassword = (index, row) => {
  ElMessageBox.prompt(`请为用户 ${row.UName} 输入新密码`, '修改密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputPlaceholder: '请输入新密码',
    inputValidator: (val) => {
      if (!val || String(val).trim().length < 6) return '密码至少6位';
      return true;
    }
  }).then(async ({ value }) => {
    const res = await axios.post('/api/v2/user/password', null, { params: { userId: row.UId, newPassword: value }})
    if (res.data.code === 200) {
      ElMessage.success('密码修改成功！')
    } else {
      ElMessage.error(res.data.msg || '密码修改失败！')
    }
  }).catch(() => {
    ElMessage.info('已取消修改密码操作！')
  })
}

onMounted(() => {
  getUserList()
})
</script>

<template>
  <div class="user-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">用户管理</h1>
          <p class="page-subtitle">管理系统用户和权限</p>
        </div>
        <div class="header-right">
          <div class="search-section">
            <el-input 
              v-model="qq" 
              placeholder="请输入QQ号搜索" 
              clearable
              class="search-input"
              prefix-icon="Search"
            />
            <el-button 
              type="primary" 
              @click="getUserList"
              icon="Search"
            >
              查询
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalUser }}</div>
              <div class="stat-label">用户总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userList.filter(item => item.UStatus === 0).length }}</div>
              <div class="stat-label">正常用户</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userList.filter(item => item.UStatus === 1).length }}</div>
              <div class="stat-label">封禁用户</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ Math.round((userList.filter(item => item.UStatus === 0).length / totalUser) * 100) || 0 }}%</div>
              <div class="stat-label">活跃率</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <div class="table-card">
        <div class="table-header">
          <h3 class="table-title">用户列表</h3>
          <div class="table-actions">
            <el-button 
              icon="Refresh" 
              size="small"
              @click="getUserList"
            >
              刷新
            </el-button>
          </div>
        </div>
        
        <el-table 
          :data="userList" 
          class="data-table"
          stripe
          border
        >
          <el-table-column 
            align="center" 
            prop="UId" 
            label="序号"
            width="80"
          />
          <el-table-column 
            align="center" 
            prop="UName" 
            label="用户名"
            min-width="120"
          />
          <el-table-column 
            align="center" 
            prop="UQq" 
            label="QQ号"
            min-width="120"
          />
          <el-table-column 
            align="center" 
            prop="UStatus" 
            label="状态"
            width="100"
          >
            <template #default="scope">
              <el-tag 
                v-if="scope.row.UStatus === 0" 
                type="success"
                effect="dark"
              >
                正常
              </el-tag>
              <el-tag 
                v-if="scope.row.UStatus === 1" 
                type="danger"
                effect="dark"
              >
                封禁中
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="280"
            align="center"
          >
            <template #default="scope">
              <el-button 
                type="warning" 
                size="small"
                v-if="scope.row.UStatus === 0" 
                @click="handleBan(scope.$index, scope.row)"
                icon="Lock"
              >
                封禁
              </el-button>
              <el-button 
                type="success" 
                size="small"
                v-if="scope.row.UStatus === 1" 
                @click="handleUnban(scope.$index, scope.row)"
                icon="Unlock"
              >
                解封
              </el-button>
              <el-button 
                type="primary" 
                size="small"
                @click="handleResetPassword(scope.$index, scope.row)"
                icon="Edit"
              >
                改密
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleDelete(scope.$index, scope.row)"
                icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalUser"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-management-container {
  min-height: 100%;
}

/* 页面头部 */
.page-header {
  margin-bottom: 2rem;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background: var(--gradient-card);
  border-radius: 12px;
  border: 1px solid var(--border-gold);
  box-shadow: 0 4px 12px var(--shadow-dark);
}

.page-title {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--gold-primary);
  background: var(--gradient-gold);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  margin: 0.5rem 0 0 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.search-section {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.search-input {
  width: 200px;
}

/* 统计卡片 */
.statistics-section {
  margin-bottom: 2rem;
}

.stat-card {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 4px 12px var(--shadow-dark);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px var(--shadow-gold);
}

.stat-icon {
  width: 60px;
  height: 60px;
  background: var(--gradient-gold);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-black);
  font-size: 1.5rem;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: var(--gold-primary);
  line-height: 1;
  margin-bottom: 0.5rem;
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 表格区域 */
.table-section {
  margin-bottom: 2rem;
}

.table-card {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px var(--shadow-dark);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-dark);
}

.table-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--text-primary);
}

.data-table {
  width: 100%;
}

.pagination-wrapper {
  padding: 1.5rem;
  display: flex;
  justify-content: center;
  border-top: 1px solid var(--border-dark);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .search-section {
    flex-direction: column;
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
  
  .statistics-section .el-col {
    margin-bottom: 1rem;
  }
  
  .table-header {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>